package com.bluefox.hospital.convertor;

import com.bluefox.common.web.dto.AbstractConvertor;
import com.bluefox.hospital.dto.AnnouncementDTO;
import com.bluefox.hospital.model.Announcement;
import com.bluefox.hospital.service.AnnouncementService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.util.Date;

/**
 * AnnouncementConvertor
 */
@Component
public class AnnouncementConvertor extends AbstractConvertor<Announcement, AnnouncementDTO> {

    @Autowired
    private AnnouncementService announcementService;

    @Override
    public Announcement toModel(@NonNull final AnnouncementDTO dto) {
        if (dto.isNew()) {//新增
            return constructModel(dto);
        } else {//更新
            return updateModel(dto);
        }
    }

    @Override
    public AnnouncementDTO toDTO(@NonNull final Announcement model, final boolean forListView) {
        final AnnouncementDTO dto = new AnnouncementDTO();
        dto.setId(model.getId());
        dto.setTitle(model.getTitle());
        dto.setContent(model.getContent());
        dto.setDate1(model.getDate1());
        dto.setDate2(model.getDate2());
        dto.setCreatedDate(Date.from(model.getCreatedDate().get().atZone(ZoneId.systemDefault()).toInstant()));
        dto.setType(model.getType());
        dto.setVisitors(model.getVisitors());
        dto.setStatus(model.getStatus());
        dto.setCreatedBy(model.getCreatedBy().get());
        dto.setOrderField(model.getOrderField());
        return dto;
    }

    // 构建新Model
    private Announcement constructModel(final AnnouncementDTO dto) {
        Announcement model = new Announcement();
        return getAnnouncement(dto, model);
    }

    // 更新Model
    private Announcement updateModel(final AnnouncementDTO dto) {
        Announcement model = announcementService.get(dto.getId());
        return getAnnouncement(dto, model);
    }

    private Announcement getAnnouncement(AnnouncementDTO dto, Announcement model) {
        model.setTitle(dto.getTitle());
        model.setContent(dto.getContent());
        model.setDate1(dto.getDate1());
        model.setDate2(dto.getDate2());
        model.setType(dto.getType());
        model.setVisitors(dto.getVisitors());
        model.setStatus(dto.getStatus());
        model.setOrderField(dto.getOrderField());
        return model;
    }
}
